from django.http import JsonResponse

from comment.comservice import add_filter
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from .sqlmap import *

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


def all_performance_classify(params):
    """
    查询所有绩效分类
    :param params:
    :return:
    """
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    sql = PerformanceSqlMap.FIND_ALL_CLASSIFY.format(**params)
    result_all = mysql_tools.select_all(sql)
    return success_response(result_all)


def all_performance(params):
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if not val:
    #         return err_response(210, "%s参数缺失" % key)
    sql_all = PerformanceSqlMap.FIND_BY_USER_ID.format(**params)
    result_all = mysql_tools.select_one(sql_all)
    return success_response(result_all)


def add_or_sub_performance(params):
    dict = {
        "user_id": "user_id",
        "add_or_sub": "add_or_sub"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    sql_add_or_sub = PerformanceSqlMap.list_add_or_sub.format(**params)
    sql_add_or_sub += " order by t3.create_time desc"
    result = mysql_tools.select_all(sql_add_or_sub)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        res["create_time"] = str(res["create_time"])
    return success_response(result)


def subordinates_performance(params):  # 下属绩效
    dict = {
        "user_id": "user_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str_sub": "query_str"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    sql_my_role = PerformanceSqlMap.FIND_ROLE.format(**params)
    my_role = mysql_tools.select_one(sql_my_role)
    if not my_role is None:
        my_role = my_role.get("role_value")
    params["my_role"] = my_role
    if my_role <= 1:
        sql_all = PerformanceSqlMap.subordinates_performance_all
    else:
        sql_all = PerformanceSqlMap.subordinates_performance_sub
    sql = add_filter(sql_all, params, ["query_str_sub"], **PerformanceSqlMap.FILTER_PARAMS)

    result = mysql_tools.select_all(sql.format(**params))
    if not result:
        return success_response([])
    if params.get("isall") != 1:
        if isinstance(result,JsonResponse):
            return result
        result = paging_simple(result, params.get("page"), params.get("size"))
    return success_response(result)


def subordinates_add_or_sub(params):
    dict = {
        "father_id": "user_id",  # 当前用户id
        "performance_id": "performance_id",
        "user_id": "subordinates_id"  # 下属id
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if val is None:
    #         return err_response(210,"%s参数缺失" % key)
    sql_pool_check = PerformanceSqlMap.subordinates_pool_check.format(**params)
    pool_check = mysql_tools.select_one(sql_pool_check, msg="performance_id参数错误")
    if isinstance(pool_check, JsonResponse):
        return pool_check
    pool_check["is_active"] = int.from_bytes(pool_check["is_active"], byteorder='big')
    pool_check["add_or_sub"] = int.from_bytes(pool_check["add_or_sub"], byteorder='big')
    if pool_check["is_active"] == 0:
        return err_response(210)
    val = {
        "add_or_sub": pool_check["add_or_sub"],
        "record": pool_check["record"],
        "user_id": params["user_id"]
    }
    if pool_check["add_or_sub"] == 0:
        mysql_tools.execute_sql(PerformanceSqlMap.subordinates_pool_update1.format(**val))
    else:
        mysql_tools.execute_sql(PerformanceSqlMap.subordinates_pool_update2.format(**val))
    sql_add_or_sub = PerformanceSqlMap.subordinates_add_or_sub.format(**params)
    mysql_tools.execute_sql(sql_add_or_sub, commit=True)
    return success_response()


# def performance_appraisal(params):
#     dict = {
#         "user_id": "user_id"
#     }
#     page_params = {
#         "isall": "isAll",
#         "size": "limit",
#         "page": "page"
#     }
#     params = get_params(params, dict, page_params)
#     if isinstance(params, JsonResponse):
#         return params
#     result = mysql_tools.select_all(PerformanceSqlMap.performance_appraisal)
#     if params.get("isall") is not True:
#         result = paging_simple(result, params.get("page"), params.get("size"))
#     if not result:
#         return success_response([])
#     for res in result:
#         res["add_or_sub"] = int.from_bytes(res["add_or_sub"], byteorder='big')
#         res["is_active"] = int.from_bytes(res["is_active"], byteorder='big')
#         if res["is_active"] == 1:
#             res["is_active"] = "启用"
#         else:
#             res["is_active"] = "禁用"
#         if res["add_or_sub"] == 1:
#             res["record"] = -res["record"]
#     return success_response(result)


def performance_appraisal(params):
    dict = {
        "user_id": "user_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "status_id": "status_id",
        "add_or_sub": "add_or_sub",
        "query_str": "query_str"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    sql = PerformanceSqlMap.performance_appraisal
    sql = add_filter(sql, filter_params=["status_id", "add_or_sub", "query_str"], body_params=params,
                     **PerformanceSqlMap.FILTER_PARAMS)
    sql = sql.format(**params)
    result = mysql_tools.select_all(sql)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        res["add_or_sub"] = int.from_bytes(res["add_or_sub"], byteorder='big')
        res["is_active"] = int.from_bytes(res["is_active"], byteorder='big')
        if res["add_or_sub"] == 1:
            res["record"] = -res["record"]
        if res["is_active"] == 1:
            res["is_active"] = "启用"
        else:
            res["is_active"] = "禁用"
    return success_response(result)


def performance_create(params):
    dict = {
        "add_or_sub": "add_or_sub",
        "content": "content",
        "is_active": "is_active",
        "record": "record",
        "classify": "status_id",
        "dept_id": "dept_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if val is None:
    #         return err_response(210, "%s参数缺失" % key)
    sql_create = PerformanceSqlMap.performance_create.format(**params)
    mysql_tools.execute_sql(sql_create)
    id = mysql_tools.select_one(PerformanceSqlMap.GET_ID).get("id")
    return success_response({"performance_id": id})


def performance_edit(params):
    dict = {
        "id": "id",
        "add_or_sub": "add_or_sub",
        "content": "content",
        "is_active": "is_active",
        "record": "record",
        "classify": "status_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if val is None:
    #         return err_response(210, "%s参数缺失" % key)
    sql_edit = PerformanceSqlMap.performance_edit.format(**params)
    mysql_tools.execute_sql(sql_edit, commit=True)
    return success_response()


def performance_rank(params):
    dict = {
        "user_id": "user_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if key in ["isall", "size", "page"]:
    #         continue
    #     if not val:
    #         return err_response(210, "%s参数缺失" % key)
    sql = PerformanceSqlMap.performance_rank
    result = mysql_tools.select_all(sql)
    if params.get("isall") != 1:
        if isinstance(result,JsonResponse):
            return result
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for key, val in enumerate(result):
        val["id"] = key + 1
    return success_response(result)


def other_record(params):
    dict = {
        "user_id": "user_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210, "user_id参数缺失")
    sql_list_other = PerformanceSqlMap.list_other.format(**params)
    sql_list_other += " order by t3.create_time desc"
    result = mysql_tools.select_all(sql_list_other)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    if isinstance(result,JsonResponse):
        return result
    for res in result:
        res["create_time"] = str(res["create_time"])
        res["add_or_sub"] = int.from_bytes(res["add_or_sub"], byteorder='big')
    return success_response(result)


def my_record(params):
    dict = {
        "user_id": "user_id",
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210)
    sql_list_my = PerformanceSqlMap.list_my.format(**params)
    sql_list_my += " order by t3.create_time desc"
    result = mysql_tools.select_all(sql_list_my)
    if params.get("isall") != 1:
        if isinstance(result,JsonResponse):
            return result
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        res["create_time"] = str(res["create_time"])
        res["add_or_sub"] = int.from_bytes(res["add_or_sub"], byteorder='big')
    return success_response(result)


@format_response
def index(request):
    return com_views(request, {
        "all_performance": all_performance,
        "add_or_sub_performance": add_or_sub_performance,
        "other_record": other_record,
        "my_record": my_record,
        "subordinates_performance": subordinates_performance,
        "subordinates_add_or_sub": subordinates_add_or_sub,
        "performance_appraisal": performance_appraisal,
        # "performance_filter": performance_filter,
        "performance_create": performance_create,
        "performance_edit": performance_edit,
        "performance_rank": performance_rank,
        "all_performance_classify": all_performance_classify
    })
